﻿using System;
using System.Globalization;
using System.Web.Mvc;

namespace TSharp.Core.AppBox.CodeBase
{
    public class TSharpThemesViewEngine : WebFormViewEngine
    {

        public TSharpThemesViewEngine()
        {
            ViewLocationFormats = new[] { 
                                            "~/{0}.aspx",
                                            "~/{0}.ascx",
                                            "~/Views/{1}/{0}.aspx",
                                            "~/Views/{1}/{0}.ascx",
                                            "~/Views/Shared/{0}.aspx",
                                            "~/Views/Shared/{0}.ascx",
                                            "~/Views/Plugins/{0}.ascx",
                                        };

            MasterLocationFormats = new[] {
                                              "~/{0}.master",
                                              "~/Shared/{0}.master",
                                              "~/Views/{1}/{0}.master",
                                              "~/Views/Shared/{0}.master",
                                          };
            PartialViewLocationFormats = ViewLocationFormats;

        }
        private static Type baseControllerType = typeof(BaseController);
        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            ViewEngineResult result = null;
            var request = controllerContext.RequestContext;
            if (controllerContext.Controller.GetType().IsAssignableFrom(baseControllerType))
            {
                var orchardController = controllerContext.Controller as BaseController;
                string ThemeName = orchardController.ThemeName;
                string templatedViewName = string.Format(CultureInfo.InvariantCulture, "~/Views/Themes/{0}/{1}.aspx", ThemeName, viewName);

                masterName = string.IsNullOrEmpty(masterName) ? "Theme.master" : masterName;

                result = base.FindView(controllerContext, templatedViewName, "~/Views/Themes/" + ThemeName + "/" + masterName, useCache);
                controllerContext.HttpContext.Items["template"] = ThemeName;
            }
            else
            {
                result = base.FindView(controllerContext, viewName, masterName, useCache);
            }

            return result;
        }

    }
}